package com.swak.persistence;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.Assert;

import com.swak.define.CurdDefine;
import com.swak.utils.StringUtils;

/**
 * 拼接排序
 * 
 * @author 618lf
 */
public class OrderBy {
	private static final Pattern OrderByPattern = Pattern.compile("(\\w+)(:(\\w+))?[;]?");

	private StringBuilder orders = new StringBuilder();

	public OrderBy Asc(String column) {
		return this.by(column, CurdDefine.ASC);
	}

	public OrderBy Desc(String column) {
		return this.by(column, CurdDefine.DESC);
	}

	public OrderBy by(String column, String type) {
		Assert.isTrue(StringUtils.isNotBlank(column), "column not null");
		if (!orders.isEmpty()) {
			orders.append(CurdDefine.SPLIT);
		}
		orders.append(StringUtils.escapeDb(column));
		if (StringUtils.isNotBlank(type)) {
			orders.append(CurdDefine.SPACE).append(type);
		}
		return this;
	}

	public OrderBy orElseDesc(String column) {
		if (orders.isEmpty()) {
			this.Desc(column);
		}
		return this;
	}

	public OrderBy orElseAsc(String column) {
		if (orders.isEmpty()) {
			this.Asc(column);
		}
		return this;
	}

	public OrderBy orElse(String orderBy) {
		if (orders.isEmpty()) {
			orders.append(orderBy);
		}
		return this;
	}

	public OrderBy parse(String orderBy) {
		if (StringUtils.isNotBlank(orderBy)) {
			Matcher matcher = OrderByPattern.matcher(orderBy);
			while (matcher.find()) {
				String field = StringUtils.convertProperty2Column(matcher.group(1));
				String type = matcher.group(3);
				this.by(field, type);
			}
		}
		return this;
	}

	@Override
	public String toString() {
		return orders.toString();
	}

	public static OrderBy of() {
		return new OrderBy();
	}
}
